﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using ScytaleDecrypt.Model.Interfaces;

namespace ScytaleDecrypt.Model 
{
    public class ProcessedMessage : IDecryptable {

        
        private string sanitizedMessage;

        internal int sanitizedMessageLength; 

        public List<string> MessageParts { get; set; }

        public int SubMessageLength { get; set; }

        public int SubMessageCount { get; set; }

        public ProcessedMessage( string message , int partLength ) {
            sanitizedMessage = SanitizeMessage(message);
            sanitizedMessageLength = sanitizedMessage.Length;
            MessageParts = new List<String>();
            SubMessageLength = partLength;

            DivideMessageIntoParts(message);
            SubMessageCount = MessageParts.Count;
        }

        public List<string> Decrypt()
        {
            return Decrypter.DecryptProcessedMessages(this);
        }

        private void DivideMessageIntoParts(string message) {           
            for (int currentStartIndex = 0; currentStartIndex < sanitizedMessageLength; currentStartIndex += SubMessageLength ) {
                String subString = GetSubStringFromSanitizedMessage(currentStartIndex);
                MessageParts.Add(subString);
            }
        }

        private String SanitizeMessage( string message ) {
            String tmpMessage = message.Replace("\n", "");
            tmpMessage = tmpMessage.Replace(" ", "");
            return tmpMessage;
            
        }

        private string GetSubStringFromSanitizedMessage(int startIndex) {
            if (startIndex + SubMessageLength < sanitizedMessageLength)
            {
                return sanitizedMessage.Substring(startIndex, SubMessageLength);
           }
           else {
               int newLength = sanitizedMessageLength - startIndex;
               return sanitizedMessage.Substring(startIndex, newLength);
           }
        }



    }
}
